<?php
namespace app\myadmin\model;
use think\Model;
class Config extends Model
{
	// 时间戳配置
	protected $autoWriteTimestamp = true;
	// 定义时间戳字段名
	protected $createTime = "create_time";
	protected $updateTime = "update_time";
	// 列表
	public function index($where=[])
	{
		$array=$this->order("orders asc,id asc")
		->where($where)
		->select();
		$info=$this->buildChild(0,$array);
		return $info;
	}
	// 递归
	private function buildChild($pid,$list)
	{
		$newlist = [];
		foreach ($list as $k=>$v) {
			if ($pid == $v["pid"]) {
				if(!empty($v["content"])){
					$v["content"]=explode(",",$v["content"]);
				}
				$node = $v;
				$child = $this->buildChild($v["id"], $list);
				if (!empty($child)) {
					$node["children"] = $child;
				}
				$newlist[] = $node;
			}
		}
		return $newlist;
	}
	// 增改
	public function edit($Int,$Data)
	{
		$Data=TrimArray($Data);
		$Data["orders"] = intval($Data["orders"])?:0;
		if($Data["content"]==""){
			$Data["content"]=NULL;
		}
		$validate = new \app\myadmin\validate\Config;
		if (!$validate->check($Data)) {
			return ["code"=>1,"msg"=>$validate->getError()];
		}
		
		if($Data["pid"]==0){
			$Data["type"]=0;
		}else{
			if($Data["type"]==""){
				return ["code"=>1,"msg"=>"分类为空"];
			}elseif($Data["type"]<=2){
				$Data["content"]=NULL;
			}
		}
		if($Int==0){
			$info=$this->save($Data);
		}else{
			if($Data["pid"]==$Data["id"]){
				return ["code"=>1,"msg"=>"自我父级"];
			}
			$info=$this->update($Data);
		}
		if($info) {
			return ["code"=>0,"msg"=>"操作成功"];
		} else {
			return ["code"=>1,"msg"=>"操作失败"];
		}
	}
	// 编辑
	public function myedit($Data)
	{
		$Data=TrimArray($Data);
		if($Data["title"]==""){
			return ["code"=>1,"msg"=>"标题为空"];
		}
		$i=0;
		foreach($Data as $k=>$v){
			if(is_array($v)){
				$v=implode(",",$v);
			}
			if($this->where("name",$k)->update(["value"=>$v,"update_time"=>time()])){
				$i++;
			}
		}
		if($i>0) {
			return ["code"=>0,"msg"=>"操作成功"];
		} else {
			return ["code"=>1,"msg"=>"操作失败"];
		}
	}
}
